package com.wlf.admin.common.quartz;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.wlf.admin.common.quartz.base.BaseQuartz;
import com.wlf.admin.common.util.AjaxError;
import com.wlf.admin.system.domain.ScheduleJob;
import com.wlf.admin.system.domain.ScheduleLog;
import com.wlf.admin.system.service.ScheduleLogService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.time.LocalDateTime;

/**
 * Quartz Job 执行逻辑
 * <p>
 * 通过 className 反射生成实例, 执行任务并记录日志
 *
 * @author 就眠儀式
 * @serial 2.0.0
 */
@Slf4j
public class QuartzExecute extends QuartzJobBean {

    @Override
    protected void executeInternal(JobExecutionContext context) {
        Object o = context.getMergedJobDataMap().get(ScheduleJob.JOB_PARAM_KEY);
        ScheduleJob jobBean = (ScheduleJob) o;
        ScheduleLogService logService = SpringUtil.getBean(ScheduleLogService.class);
        ScheduleLog logBean = new ScheduleLog();
        logBean.setId(IdWorker.getId());
        logBean.setJobId(jobBean.getId());
        logBean.setBeanName(jobBean.getBeanName());
        logBean.setParams(jobBean.getParams());
        logBean.setCreateTime(LocalDateTime.now());
        long beginTime = System.currentTimeMillis();
        try {
            BaseQuartz target = SpringUtil.getBean(jobBean.getBeanName(), BaseQuartz.class);
            if (target == null) {
                AjaxError.getAndThrow("定时任务实现类不存在或以及被移除，请检查代码");
            }
            target.run(jobBean.getParams());
            long executeTime = System.currentTimeMillis() - beginTime;
            logBean.setTimes((int) executeTime);
            logBean.setStatus(0);
            log.info("定时器 === >> " + jobBean.getName() + "执行成功,耗时 === >> " + executeTime);
        } catch (Exception e) {
            long executeTime = System.currentTimeMillis() - beginTime;
            logBean.setTimes((int) executeTime);
            logBean.setStatus(1);
            if (e.getCause() != null) {
                logBean.setError(e.getCause().getMessage());
            } else {
                logBean.setError(e.getMessage());
            }
            if (StrUtil.isBlank(logBean.getError())) {
                logBean.setError("未能捕获异常信息");
            }

        } finally {
            logService.save(logBean);
        }
    }
}
